/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL
v2. You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by Wangyunlai on 2022/5/22.
//
#include "sql/stmt/update_stmt.h"

#include <cmath>
#include <iomanip>
#include <memory>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <utility>
#include <string>

#include "common/log/log.h"
#include "sql/stmt/filter_stmt.h"
#include "sql/stmt/select_stmt.h"
#include "sql/stmt/utils.h"
#include "storage/db/db.h"
#include "storage/table/table.h"
#include "storage/table/table_meta.h"

UpdateStmt::UpdateStmt(Table *table, std::vector<UpdateUnit> update_units,
                       FilterStmt *filter_stmt)
    : table_(table), update_units_(update_units), filter_stmt_(filter_stmt) {}

RC UpdateStmt::create(Db *db, UpdateSqlNode &update, Stmt *&stmt) {
  const char *table_name = update.relation_name.c_str();
  Table *table = db->find_table(table_name);
  Utils utils;

  // 校验表是否存在
  if (nullptr == table) {
    LOG_WARN("no such table. db=%s, table_name=%s", db->name(), table_name);
    return RC::SCHEMA_TABLE_NOT_EXIST;
  }
  int len = update.update_units.size();
  for (int i = 0; i < len; i++) {
    update.update_units[i].flag = 0;
  }
  for (int i = 0; i < len; i++) {
    std::string attribute_name = update.update_units[i].attribute_name;
    // 校验要更新的表的字段是否存在
    const FieldMeta *field_meta =
        table->table_meta().field(attribute_name.c_str());
    Value value = update.update_units[i].value;
    if (nullptr == field_meta) {
      LOG_WARN("no such field. db=%s, table_name=%s, field_name=%s", db->name(),
               table_name, attribute_name);
      return RC::SCHEMA_FIELD_NOT_EXIST;
    }
    const AttrType field_type = field_meta->type();
    AttrType value_type = value.attr_type();
    if (value_type == UNDEFINED) {
      std::vector<Value> values;
      Stmt *select_stmt;
      RC rc;
      rc = SelectStmt::create(db, update.update_units[i].sub_select,
                              select_stmt);
      if (rc != RC::SUCCESS) {
        return rc;
      }
      bool flag = false;
      rc = utils.get_value(select_stmt, values, db, flag);
      if (rc != RC::SUCCESS) {
        return rc;
      }
      if (values.size() > 1 || flag) {
        Value tmp;
        tmp.set_null();
        update.update_units[i].value = tmp;
        update.update_units[i].flag = -1;
      } else if (values.size() == 0) {
        Value tmp;
        tmp.set_null();
        update.update_units[i].value = tmp;
      } else {
        update.update_units[i].value = values[0];
      }
      value_type = update.update_units[i].value.attr_type();
      value = update.update_units[i].value;
    }

    if (!field_meta->nullable() &&
        update.update_units[i].value.attr_type() == NULLS) {
      return RC::SCHEMA_FIELD_TYPE_MISMATCH;
    }
    if (OB_SUCC(field_type_compare_compatible_table(
            field_type, update.update_units[i].value.attr_type()))) {
      if (OB_FAIL(convert_value_to_field(field_type,
                                         update.update_units[i].value)) &&
          update.update_units[i].value.attr_type() != NULLS) {
        return RC::UNIMPLENMENT;
      }
      /*if (field_meta->type() == value_type && value_type == AttrType::CHARS) {
        if (field_meta->len() < value.length()) {
          sql_debug("invalid argument,field_meta_len is %d, value_len is
      %d",field_meta->len(),value.length()); return RC::INVALID_ARGUMENT;
        }
      }*/
    } else {
      return RC::SCHEMA_FIELD_TYPE_MISMATCH;
    }
  }

  std::unordered_map<std::string, Table *> table_map;
  table_map.insert(
      std::pair<std::string, Table *>(std::string(table_name), table));

  FilterStmt *filter_stmt = nullptr;
  RC rc = FilterStmt::create(db, table, &table_map, update.conditions.data(),
                             static_cast<int>(update.conditions.size()),
                             filter_stmt);
  if (rc != RC::SUCCESS) {
    LOG_WARN("failed to create filter statement. rc=%d:%s", rc, strrc(rc));
    return rc;
  }

  stmt = new UpdateStmt(table, update.update_units, filter_stmt);
  return RC::SUCCESS;
}
